import { KwLogger } from "./../logger/index";
import { Response, Request } from "express";
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import { parseId } from "../utils";
import * as moment from "moment";
import * as _ from 'lodash';
import { Logger } from "../logger";

// 捕获所有的异常， 如果捕获特定的异常可传入参数, 如 @Catch(HttpException) 捕获 Http 异常
@Catch()
export class HExceptionFilter implements ExceptionFilter<Error> {
  private readonly logger: KwLogger = new KwLogger();
  catch(exception: Error, host: ArgumentsHost) {
      const ctx = host.switchToHttp();
      const request = ctx.getRequest<Request>();
      const response = ctx.getResponse<Response>();

      const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
      const message = exception instanceof HttpException ? exception.getResponse() : exception.message ? exception.message : `${status >= 500 ? '服务器错误(Service Error)' : '客户端错误(Client Error)'}`;

      const url = request.url;
      const oid = parseId().toString();
      const errorResponse = {
        code: status,
        oid,
        message
      }

      // 日志记录
      const now = new Date().getTime();
      const method = request.method;
      const params = Object.assign({}, request.params, request.body, request.query);
      const loggerObj: Logger = {
        oid,
        status,
        datetime: moment(now).format('YYYY-MM-DD HH:mm:ss'),
        method,
        url,
        params,
        stack: exception.stack
      }
      this.logger.error(loggerObj);

      // 发现异常，结束请求，发送响应
      response
        .status(status)
        .json(errorResponse);
  }
}